package unamur.iodass.delivery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

import org.apache.log4j.Logger;

import unamur.iodass.communication.Communication;
import unamur.iodass.communication.messages.CancelDeliver;
import unamur.iodass.communication.messages.Deliver;


public class DeliveryHandler {

	private static final Logger logger = Logger.getLogger(DeliveryHandler.class);

	private ArrayList<Deliver> booksToDeliver;

	private static volatile DeliveryHandler instance;

	public static DeliveryHandler getInstance() {
		if (instance == null) {
			synchronized (DeliveryHandler.class) {
				if (instance == null) {
					instance = new DeliveryHandler();
				}
			}
		}
		return instance;
	}

	private DeliveryHandler() {
		booksToDeliver = new ArrayList<Deliver>();
	}

	public void showOnTerminal() {

		System.out.println("\n\n Liste des livres à livrer\n");
		
		for (int i=0; i<booksToDeliver.size(); i++){
			Deliver deliver = booksToDeliver.get(i);
			System.out.println("\t ["+ i +"] \t" + deliver.getIsbn() + "\t " + deliver.getClient().getNom() + "\t " + deliver.getBookstore().getName());
		}


		Scanner in = new Scanner(System.in);

		int id = -1;
		do {
			System.out.print("Entrez l'indice de la délivraison à annuler: " );
			id = in.nextInt();
		} while (id < 0 || id > booksToDeliver.size()-1);

		System.out.println("Number : " + id);

		if (id >= 0 && id <= booksToDeliver.size()-1) {
			logger.info("CancelDelivery "+ "\t " +  
					booksToDeliver.get(id).getIsbn() +
					"\t " + booksToDeliver.get(id).getClient().getNom() + "\t " 
					+ booksToDeliver.get(id).getBookstore().getName());
			
			
			CancelDeliver cancel = new CancelDeliver(
					booksToDeliver.get(id).getIsbn(), booksToDeliver.get(id).getClient(), booksToDeliver.get(id).getBookstore());

			// envoi de l'object CancelDeliver au BookStore concerné
			Communication.getInstance().async(
					cancel, booksToDeliver.get(id).getBookstore().getIp(), 
					booksToDeliver.get(id).getBookstore().getPort());
			
		
			booksToDeliver.remove(id);
		}




	}


	public void saveDelivery(Deliver deliver) {
		logger.info("NEW BOOK TO DELIVER :\t " + deliver.getIsbn() +"\t "+ deliver.getClient().getNom() +"\t "+ deliver.getBookstore().getName());

		booksToDeliver.add(deliver);
	}


}
